<template>
  <div class="ChatPageApp">
    <main class="ChatPage-m-content">
      <div class="container">
        <section class="chatbox-container">
          <div class="chat-header">
            <el-button icon="ArrowLeft" class="arrow-button" circle @click="goBack"></el-button>
            <div class="chat-title">
              <h3>{{ title }}</h3>
              <p>共{{ length }}条对话</p>
            </div>
          </div>
          <div v-show="!playId">
            <video style="width: 100%">
              <source src="@/assets/video/2.mp4">
            </video>
          </div>
          <div v-show="playId">
            <video style="width: 100%" autoplay>
              <source src="@/assets/video/1.mp4">
            </video>
          </div>
          <div class="chatbox" id="scroll">
            <div
              :class="{
                'chat-content1': msg.role === 1,
                'chat-content0': msg.role === 0
              }" v-for="(msg, index) in messages" :key="index">
              <div class="chat-message">
                <div class="message-content-1" v-show="msg.role === 1">{{ msg.text }}</div>
                <div class="message-content-0" v-show="msg.role === 0">
                  <v-md-preview :text="msg.text"></v-md-preview>
                </div>
              </div>
            </div>
          </div>
          <div class="chat-input">
            <div class="chatbox-button-group">
              <el-button circle icon="QuestionFilled"></el-button>
              <el-button circle icon="Tools"></el-button>
              <el-button circle icon="MagicStick"></el-button>
              <el-button circle icon="DeleteFilled"></el-button>
            </div>
            <div class="input-wrapper">
              <el-input
                v-model="input"
                type="textarea"
                placeholder="在此输入"
                @keydown="keyDown"
                class="custom-textarea"
              ></el-input>
              <el-button
                type="primary"
                icon="Promotion"
                @click="sendMessage"
                class="send-button"
              >发送</el-button>
            </div>
          </div>
        </section>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">

import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useRoute } from 'vue-router'

const input = ref('')
const title = ref('请开始一个新的对话')
const nowTitleId = ref(-1)
const length = ref(0)
const messages = reactive([])
const dialogs = reactive([])

const cnt = ref(0)

const playId = ref(1)

const talk1 = ref('你好，我是你的学习智教助手小A，你有什么疑问或者知识点想要学习呢？')

const talk2 = ref('分治法的基本思想可以归纳为以下几点：\n' +
  '1.**问题分解**：对于一个难以直接解决的规模较大的问题，将其分解成若干个规模较小的、相互独立的、且与原问题性质相同的子问题。这是分治法最核心的步骤，通过问题的分解，可以简化问题的复杂度，使其更易于解决。\n' +
  '2.**递归分解**：对于分解后的子问题，采用递归的方式进行求解。即，如果子问题的规模仍然较大，可以继续将其分解为更小的子问题，并递归地求解这些更小的子问题，直到子问题的规模足够小，可以直接求解为止。\n' +
  '3.**合并解**：在得到所有子问题的解之后，将这些解合并起来，形成原问题的解。合并解的过程中可能需要进行一些额外的计算或处理，以确保得到的解是正确的。\n' +
  '总的来说，分治法通过“分而治之”的策略，将复杂问题简化为若干简单问题来求解，从而有效地降低了问题的复杂度。这种方法在计算机科学、数学、工程学等领域都有广泛的应用。\n' +
  '需要注意的是，虽然分治法能够显著降低问题的复杂度，但它并不总是适用的。在使用分治法之前，需要仔细分析问题的性质，确保问题可以被有效地分解为若干独立的子问题，并且这些子问题的解可以正确地合并成原问题的解。')

const goBack = () => {
  router.push('/chatlist');
}

const formatDate = (date: Date, format = 'yyyy-MM-dd HH:mm:ss'): string => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const formatMap: { [key: string]: any } = {
    yyyy: year.toString(),
    MM: month.toString().padStart(2, '0'),
    dd: day.toString().padStart(2, '0'),
    HH: hour.toString().padStart(2, '0'),
    mm: minute.toString().padStart(2, '0'),
    ss: second.toString().padStart(2, '0')
  }
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => formatMap[match])
}

const scrollToBottom = async () => {
  const div = document.getElementById('scroll');
  console.log('测试', div.scrollTop, div.scrollHeight)
  await div && (div.scrollTop = div.scrollHeight)
  console.log('测试', div.scrollTop, div.scrollHeight)
}

const getThisDialog = async (titleId) => {
  console.log('titleId', titleId)
  nowTitleId.value = titleId
  messages.splice(0)
  await axios.get('student/AI/onlyConversation?titleId=' + titleId)
    .then(res => {
      console.log(res)
      title.value = res.data.data.title
      length.value = res.data.data.onlyConversationVOList.length
      for (let i = res.data.data.onlyConversationVOList.length - 1; i >= 0; i --) {
        messages.push({
          text: res.data.data.onlyConversationVOList[i].content,
          role: res.data.data.onlyConversationVOList[i].role,
          time: res.data.data.onlyConversationVOList[i].createTime
        })
      }
      scrollToBottom()
    })
  // messages.push({
  //   text: talk1.value,
  //   role: 0,
  //   time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
  // })
}

const getDialog = async () => {
  dialogs.splice(0)
  await axios.get('student/AI/allConversation')
    .then(res => {
      console.log(res.data.data)
      for (let i = 0; i < res.data.data.length; i ++) {
        dialogs.push({
          titleId: res.data.data[i].titleId,
          title: res.data.data[i].title,
          date: res.data.data[i].newTime,
          total: res.data.data[i].total
        })
      }
    })
}

const route = useRoute()

onMounted( async () => {
  getDialog()
  let id = route.params.TitleId
  console.log(route.params)
  getThisDialog(id)
})

const tempInput = ref('');

const sendMessage = async () => {
  if (nowTitleId.value === -1) {
    ElMessage({
      message: '请选择一个对话或者创建一个对话',
      type: 'warning'
    })
    return
  }
  if (input.value.trim()) {
    messages.push({
      text: input.value,
      role: 1,
      time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
    }); // 将用户消息添加到消息数组
    tempInput.value = input.value;
    input.value = '';
    messages.push({
      text: '...',
      role: 0,
      time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
    })
    scrollToBottom();
    await axios.post('student/AI/receive', {
      titleId: nowTitleId.value,
      content: tempInput.value
    })
      .then(res => {
        messages.pop();
        messages.push({
          text: res.data.data,
          role: 0,
          time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
        })
        for (let i = 0; i < dialogs.length; i ++) {
          if (dialogs[i].titleId === nowTitleId.value) {
            dialogs[i].total = dialogs[i].total + 2
          }
        }
      })
    // if(cnt.value === 0) {
    //   messages.push({
    //     text: talk2.value,
    //     role: 0,
    //     time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
    //   })
    //   playId.value = !playId.value
    //   document.querySelector("video").play();
    // }
      playId.value = !playId.value
      document.querySelector("video").play();
    scrollToBottom();
    console.log(messages)
  }
}

const keyDown = (e) => {
  if (!e.shiftKey && e.keyCode == 13) {
    e.cancelBubble = true; //ie阻止冒泡行为
    e.stopPropagation();//Firefox阻止冒泡行为
    e.preventDefault(); //取消事件的默认动作*换行
    //以下处理发送消息代码
    sendMessage();
  }
}

</script>

<style>
.ChatPageApp {
  display: flex;
  height: 100vh;
  width: 100%;
}
.ChatPage-m-content {
  flex: 1;
  display: flex;
  padding: 0;
  background-color: #ffffff;
}
.container {
  display: flex;
  width: 100%;
}
.chat-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}

.chat-title {
  display: flex;
  flex-direction: column;
}

.chat-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.chat-title p {
  margin: 0;
  font-size: 14px;
  color: #999;
}
.chatbox-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.chat-header {
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}
.chatbox {
  display: flex;
  flex-direction: column;
  gap: 5px;
  height: 50%;
  overflow-y: scroll; /* 超出内容时有滚动条 */
}
.chat-content0 {
}
.chat-content1 {
  display: flex;
  justify-content: flex-end;
}
.chat-message {
  display: flex;
  align-items: center;
  margin: 10px;
}
.message-content-0 {
  background-color: #f4f4f4;
  max-width: 1250px;
  text-align: left;
  padding: 10px;
  margin: 5px;
  border-radius: 10px;
}
.message-content-1 {
  background-color: #409eff;
  max-width: 1250px;
  color: white;
  text-align: left;
  padding: 10px;
  margin: 5px;
  border-radius: 10px;
}
.chat-input {
  background-color: white;
  position: fixed;
  width: 100%;
  padding: 0;
  bottom: 0.5em;
}

.chatbox-button-group {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  margin-bottom: 10px;
  padding-left: 10px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.custom-textarea {
  width: 100%;
  height: 100%;
  padding: 0;
  padding-right: 100px;
  border-radius: 10px;
  resize: none;
  box-sizing: border-box;
  font-size: 20px;
}


.send-button {
  position: absolute;
  right: 2%;
  top: 50%;
  transform: translateY(-50%);
  padding: 5px 10px;
  width: 100px;
  height: 40px;
  color: #fff;
  background-color: #409eff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-button:hover {
  background-color: #0056b3;
}

.vuepress-markdown-body {
  padding: 0 !important;
  background-color: #f4f4f4 !important;
}
</style>
